package com.tsinkai.ettp.practice;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESPra {
	public static String src = "hello";
	
	public static void main(String[] args) {
		jdkAES();
	}
	
	public static void jdkAES() {
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			keyGenerator.init(128);
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] keyBytes = secretKey.getEncoded();
			System.out.println("key0:" + Base64.encodeBase64String(keyBytes));
			//key转化
			Key key = new SecretKeySpec(keyBytes, "AES");
			System.out.println("key:" + Base64.encodeBase64String(key.getEncoded()));
			//加密
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] result = cipher.doFinal(src.getBytes());
			System.out.println("加：" + result.length);
			System.out.println("jdk AES encrypt:"+Base64.encodeBase64String(result));
			
			//解密
			cipher.init(Cipher.DECRYPT_MODE, key);
			System.out.println("解："+Base64.decodeBase64(Base64.encodeBase64String(result)).length);
			result = cipher.doFinal(Base64.decodeBase64(Base64.encodeBase64String(result)));
			System.out.println("jdk AES decrypt:" + new String(result));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}
